package com.huatai.datacenter.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.huatai.datacenter.entity.DataSourceEntity;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Lion
 * @date 2023/3/13  13:52
 */
public class PoolManager {

	//创建lock锁
	private static Lock lock = new ReentrantLock();

	private static Lock deleteLock = new ReentrantLock();

	//所有数据源的连接池存在map里
	static Map<String, DruidDataSource> map = new HashMap<>();

	public static DruidDataSource getJDBCConnectionPool(DataSourceEntity ds){

		if (map.containsKey(ds.getId())){
			return map.get(ds.getId());
		}else {
			lock.lock();
			try{
				if (!map.containsKey(ds.getId())){
					DruidDataSource druidDataSource = new DruidDataSource();
					druidDataSource.setName(ds.getConnectName());
					druidDataSource.setUrl(ds.getUrl());
					druidDataSource.setUsername(ds.getUsername());
					druidDataSource.setPassword(ds.getPassword());
					druidDataSource.setDriverClassName(ds.getDriver());
					druidDataSource.setConnectionErrorRetryAttempts(3);
					druidDataSource.setBreakAfterAcquireFailure(true);

					map.put(ds.getId().toString(),druidDataSource);
				}
				return map.get(ds.getId());
			}catch (Exception e){
				return null;
			}finally {
				lock.unlock();
			}
		}
	}

	public static DruidPooledConnection getPooledConnection(DataSourceEntity ds) throws SQLException {
		DruidDataSource pool = PoolManager.getJDBCConnectionPool(ds);
		DruidPooledConnection connection = pool.getConnection();
		return connection;
	}

}
